package com.mxnet.chongjin.supoman.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.mxnet.chongjin.supoman.MainActivity;
import com.mxnet.chongjin.supoman.R;
import com.mxnet.chongjin.supoman.bean.RepairRecord;
import com.mxnet.chongjin.supoman.config.Api;
import com.mxnet.chongjin.supoman.style.CircleImageView;
import com.mxnet.chongjin.supoman.style.XDialog;
import com.mxnet.chongjin.supoman.utils.BitmapUtils;
import com.mxnet.chongjin.supoman.utils.LoggerUtils;
import com.mxnet.chongjin.supoman.utils.ToastUtils;
import com.mxnet.chongjin.supoman.utils.UploadUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import okhttp3.Call;

public class UserInfoActivity extends AppCompatActivity implements View.OnClickListener, UploadUtils.OnUploadProcessListener {
    private Context mContext;
    private LinearLayout mLinearLayout;
    private FrameLayout mFrameLayout1, mFrameLayout2, mFrameLayout3;
    private TextView mTextView, mTvNickname, mTvEmail;
    private CircleImageView mIvHead;
    private SharedPreferences mPreferences;
    private SharedPreferences.Editor mEditor;
    public static final int FLAG_TAKE_PHOTO = 0;
    public static final int FLAG_CHOOSE_IMG = 1;
    public static final int FLAG_OTHER = 2;
    private File file;
    private String photoPath;
    private static final int REQUEST_CAMERA = 0;
    private static final String SAVED_IMAGE_PATH = "test";
    private boolean isLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        mContext = UserInfoActivity.this;
        mPreferences = getSharedPreferences("supoman", MODE_PRIVATE);
        mEditor = mPreferences.edit();
        isLogin = mPreferences.getBoolean("isLogin", false);
        initView();
        initData();
    }

    public void initView() {
        mLinearLayout = findViewById(R.id.ll_user_info);
        mLinearLayout.setOnClickListener(this);

        mFrameLayout1 = findViewById(R.id.fl_user_info_headimage);
        mFrameLayout1.setOnClickListener(this);

        mFrameLayout2 = findViewById(R.id.fl_user_info_nickname);
        mFrameLayout2.setOnClickListener(this);

        mFrameLayout3 = findViewById(R.id.fl_user_info_email);
        mFrameLayout3.setOnClickListener(this);

        mTextView = findViewById(R.id.tv_user_info_quit_login);
        mTextView.setOnClickListener(this);

        mTvNickname = findViewById(R.id.tv_user_info_nickname);
        mTvNickname.setText(mPreferences.getString("userName", ""));

        mTvEmail = findViewById(R.id.tv_user_info_email);
        mTvEmail.setText(mPreferences.getString("userCode", ""));

        mIvHead = findViewById(R.id.iv_user_info_head);
        Glide.with(mContext).load(Api.URL_HEADER + Api.GET_IMAGE + mPreferences.getString("userImgUrl", "20180516144037.png")).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(mIvHead);
    }

    public void initData() {

    }

    @Override
    public void onClick(View v) {
        final Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.ll_user_info:
                Intent in = new Intent();
                in.setClass(mContext, MainActivity.class);
                startActivityForResult(in,20);
                finish();
                break;
            case R.id.fl_user_info_headimage:
                if (isLogin) {
                    XDialog xDialog = new XDialog(mContext, R.layout.xdialog_change_head_img, new int[]{R.id.btn_change_head_img_take_photo, R.id.btn_change_head_img_choose_from_photoalbum, R.id.btn_change_head_img_cancel});
                    xDialog.setCanceledOnTouchOutside(true);
                    xDialog.setOnXDialogItemClickListener(new XDialog.OnXDialogItemClickListener() {
                        @Override
                        public void OnXDialogItemClick(XDialog xDialog, View view) {
                            switch (view.getId()) {
                                case R.id.btn_change_head_img_take_photo:
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                        applyWritePermission();
                                    } else {
                                        jsPath();
                                    }
                                    break;
                                case R.id.btn_change_head_img_choose_from_photoalbum:
                                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                                        int hasWriteContactsPermission = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
                                        if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
                                            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 123);
                                            return;
                                        }
                                    }
                                    Intent intent1 = new Intent(Intent.ACTION_PICK);
                                    intent1.setType("image/*");
                                    startActivityForResult(intent1,
                                            FLAG_CHOOSE_IMG);
                                    break;
                                case R.id.btn_change_head_img_cancel:
                                    break;
                            }
                            xDialog.dismiss();
                        }
                    });
                    xDialog.show();
                } else {
                    ToastUtils.showToast(mContext, "请先登录！");
                }
                break;
            case R.id.fl_user_info_nickname:
                if (isLogin) {
                    intent.setClass(mContext, ChangeNicknameActivity.class);
                    mContext.startActivity(intent);
                } else {
                    ToastUtils.showToast(mContext, getResources().getString(R.string.login_first));
                }
                break;
            case R.id.fl_user_info_email:
                if (isLogin) {
                    intent.setClass(mContext, EmailActivity.class);
                    mContext.startActivity(intent);
                } else {
                    ToastUtils.showToast(mContext, getResources().getString(R.string.login_first));
                }
                break;
            case R.id.tv_user_info_quit_login:
                if (isLogin) {
                    XDialog xDialog2 = new XDialog(mContext, R.layout.xdialog_quit_login, new int[]{R.id.btn_xdialog_quit_login, R.id.btn_quit_login_cancel});
                    xDialog2.setCanceledOnTouchOutside(true);
                    xDialog2.setOnXDialogItemClickListener(new XDialog.OnXDialogItemClickListener() {
                        @Override
                        public void OnXDialogItemClick(XDialog xDialog, View view) {
                            switch (view.getId()) {
                                case R.id.btn_xdialog_quit_login:
                                    mEditor.clear();
                                    mEditor.commit();
                                    restartApplication();
                                    break;
                                case R.id.btn_quit_login_cancel:

                                    break;
                            }
                            xDialog.dismiss();
                        }
                    });
                    xDialog2.show();
                } else {
                    ToastUtils.showToast(mContext, getResources().getString(R.string.login_first));
                }
                break;
        }
    }


    /**
     * 使用相机
     */
    private void useCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/test/" + System.currentTimeMillis() + ".jpg");
        file.getParentFile().mkdirs();
        //改变Uri  com.xykj.customview.fileprovider注意和xml中的一致
        Uri uri = FileProvider.getUriForFile(this, "com.mxnet.chongjin.supoman.fileprovider", file);
        //添加权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            int hasWriteContactsPermission = checkSelfPermission(Manifest.permission.CAMERA);
            if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 123);
                return;
            }
        }
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    public void applyWritePermission() {

        String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE};

        if (Build.VERSION.SDK_INT >= 23) {
            int check = ContextCompat.checkSelfPermission(this, permissions[1]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (check == PackageManager.PERMISSION_GRANTED) {
                //调用相机
                useCamera();
            } else {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            }
        } else {
            useCamera();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10 && resultCode == RESULT_OK) {
            mTvNickname.setText(mPreferences.getString("userName", ""));
        }
        if (requestCode == 20 && resultCode == RESULT_OK) {
            mTvEmail.setText(mPreferences.getString("userCode", ""));
        }
        if (requestCode == FLAG_TAKE_PHOTO && resultCode == RESULT_OK) {
            //在手机相册中显示刚拍摄的图片
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri.fromFile(file);
                String path = contentUri.getPath();
                //文件的路径
                String absolutePath = file.getAbsolutePath();
                //文件的名字
                String parent = file.getName();
                mediaScanIntent.setData(contentUri);
                sendBroadcast(mediaScanIntent);
                //设置图片
                mIvHead.setImageBitmap(BitmapUtils.rotateBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()), 90));
                File f = BitmapUtils.saveImage("headIcon" + System.currentTimeMillis(), BitmapFactory.decodeFile(file.getAbsolutePath()));
                OkHttpUtils.post()
                        .addFile("headIcon", f.getName(), f)
                        .url(Api.URL_HEADER + Api.UPLOAD_IMG)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                ToastUtils.showToast(mContext, "更换失败！");
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                if (!TextUtils.isEmpty(response)) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        boolean success = jsonObject.optBoolean("success");
                                        if (success) {
                                            LoggerUtils.i("******** == userinfo ==", response);
                                            JSONObject data = jsonObject.optJSONObject("data");
                                            RepairRecord.ImgResourceBean imgResourceBean = new RepairRecord.ImgResourceBean();
                                            imgResourceBean.setCreateTime(data.optLong("createTime"));
                                            imgResourceBean.setFileType(data.optString("fileType"));
                                            imgResourceBean.setId(data.optString("id"));
                                            imgResourceBean.setMd5(data.optString("md5"));
                                            imgResourceBean.setName(data.optString("name"));
                                            imgResourceBean.setSize(data.optString("size"));
                                            imgResourceBean.setType(data.optString("type"));
                                            imgResourceBean.setUrl(data.optString("url"));
                                            imgResourceBean.setUserId(data.optString("userId"));
                                            mEditor.putString("userImgUrl", data.optString("url"));
                                            mEditor.commit();
                                            OkHttpUtils.post()
                                                    .url(Api.URL_HEADER + Api.CHANGE_HEADIMG)
                                                    .addParams("userId", mPreferences.getString("userId", ""))
                                                    .addParams("userImgUrl", data.optString("url"))
                                                    .build()
                                                    .execute(new StringCallback() {
                                                        @Override
                                                        public void onError(Call call, Exception e, int id) {

                                                        }

                                                        @Override
                                                        public void onResponse(String response, int id) {
                                                            if (!TextUtils.isEmpty(response)) {
                                                                try {
                                                                    JSONObject jsonObject1 = new JSONObject(response);
                                                                    boolean success = jsonObject1.optBoolean("success");
                                                                    if (success) {
                                                                        LoggerUtils.i("********", response);
                                                                        ToastUtils.showToast(mContext, "更换成功！");
                                                                    }
                                                                } catch (Exception e) {
                                                                    e.printStackTrace();
                                                                }
                                                            }
                                                        }
                                                    });
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
            } else {
                File photoFile = new File(photoPath);
                if (photoFile.exists()) {
                    //通过图片地址将图片加载到bitmap里面
                    Bitmap bm = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
                    //将拍摄的照片显示到界面上
                    //这是返回来的路径
                    //                    results.confirm(pathsa);
                    ToastUtils.showToast(mContext, "通过");
                } else {
                    ToastUtils.showToast(mContext, "图片文件不存在");
                }
            }
        } else if (requestCode == FLAG_CHOOSE_IMG && resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                mIvHead.setImageURI(uri);
                final File file1 = uri2File(uri);
                OkHttpUtils.post()
                        .addFile("headIcon",file1.getName(),file1)
                        .url(Api.URL_HEADER + Api.UPLOAD_IMG)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                ToastUtils.showToast(mContext, "更换失败！");
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                if (!TextUtils.isEmpty(response)) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        boolean success = jsonObject.optBoolean("success");
                                        if (success) {
                                            JSONObject data = jsonObject.optJSONObject("data");
                                            RepairRecord.ImgResourceBean imgResourceBean = new RepairRecord.ImgResourceBean();
                                            imgResourceBean.setCreateTime(data.optLong("createTime"));
                                            imgResourceBean.setFileType(data.optString("fileType"));
                                            imgResourceBean.setId(data.optString("id"));
                                            imgResourceBean.setMd5(data.optString("md5"));
                                            imgResourceBean.setName(data.optString("name"));
                                            imgResourceBean.setSize(data.optString("size"));
                                            imgResourceBean.setType(data.optString("type"));
                                            imgResourceBean.setUrl(data.optString("url"));
                                            imgResourceBean.setUserId(data.optString("userId"));
                                            mEditor.putString("userImgUrl", data.optString("url"));
                                            mEditor.commit();
                                            Intent intent = new Intent();
                                            intent.putExtra("userHead", data.optString("url"));
                                            setResult(56, intent);

                                            // {"code":"200","counts":0,"data":{"createTime":1532918596000,"fileType":"jpg","id":"02EE1C020E484BA99031D5550908E387","md5":"be0e3be6a90fcabff0d2536231df9926","name":"IMG_20180714_010848.jpg","size":"6093352","type":"maintain","url":"maintain/2018/07/30/04784EB3FFD9451B9B14B35BFCB0B293.jpg","userId":""},"msg":"上传成功","noLogin":false,"resp":1,"success":true}
                                            OkHttpUtils.post()
                                                    .url(Api.URL_HEADER + Api.CHANGE_HEADIMG)
                                                    .addParams("userId", mPreferences.getString("userId", ""))
                                                    .addParams("userImgUrl", data.optString("url"))
                                                    .build()
                                                    .execute(new StringCallback() {
                                                        @Override
                                                        public void onError(Call call, Exception e, int id) {

                                                        }

                                                        @Override
                                                        public void onResponse(String response, int id) {
                                                            if (!TextUtils.isEmpty(response)) {
                                                                try {
                                                                    JSONObject jsonObject1 = new JSONObject(response);
                                                                    boolean success = jsonObject1.optBoolean("success");
                                                                    if (success) {
                                                                        LoggerUtils.i("********", response);
                                                                    }
                                                                } catch (Exception e) {
                                                                    e.printStackTrace();
                                                                }
                                                            }
                                                        }
                                                    });
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
            }
        } else if (requestCode == FLAG_OTHER && resultCode == RESULT_OK) {
            if (data != null) {
                final Bitmap bitmap = data.getParcelableExtra("data");
                mIvHead.setImageBitmap(BitmapUtils.rotateBitmap(bitmap, 90));
            }
            try {
                if (file != null && file.exists())
                    file.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //裁剪图片
    private void crop(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        intent.putExtra("outputFormat", "png");
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, FLAG_OTHER);
    }

    /**
     * 拍照的，照片路径
     */
    public void jsPath() {
        //获取SD卡安装状态
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {

            //设置图片保存路径
            photoPath = SAVED_IMAGE_PATH + "/" + System.currentTimeMillis() + ".png";

            File imageDir = new File(photoPath);
            if (!imageDir.exists()) {
                try {
                    //根据一个 文件地址生成一个新的文件用来存照片
                    imageDir.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //实例化intent,指向摄像头
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //根据路径实例化图片文件
            File photoFile = new File(photoPath);
            //设置拍照后图片保存到文件中
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            //启动拍照activity并获取返回数据
            startActivityForResult(intent, REQUEST_CAMERA);
        } else {
            ToastUtils.showToast(mContext, "SD卡未插入");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            useCamera();
        } else {
            // 没有获取 到权限，从新请求，或者关闭app
//            ToastUtils.showToast(mContext, "需要存储权限");
        }
    }

    private void restartApplication() {
        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

    public void upLoadHeadImg(File filepath, String fileKey, String url) {
        UploadUtils uploadUtils = UploadUtils.getInstance();
        uploadUtils.setOnUploadProcessListener(this);
        Map<String, String> params = new HashMap<String, String>();//上传map对象
        uploadUtils.uploadFile(filepath, fileKey, url, params);
    }

    @Override
    public void onUploadDone(int responseCode, String message) {

    }

    @Override
    public void onUploadProcess(int uploadSize) {

    }

    @Override
    public void initUpload(int fileSize) {

    }

    private File uri2File(Uri uri) {
        String img_path;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null,
                null, null);
        if (actualimagecursor == null) {
            img_path = uri.getPath();
        } else {
            int actual_image_column_index = actualimagecursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();
            img_path = actualimagecursor
                    .getString(actual_image_column_index);
        }
        File file = new File(img_path);
        return file;
    }

    /** * android上传文件到服务器
     * @param file 需要上传的文件
     * @param RequestURL 请求的rul
     * @return 返回响应的内容
     */
    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10*10000000; //超时时间
    private static final String CHARSET = "utf-8"; //设置编码
    public static final String SUCCESS="1";
    public static final String FAILURE="0";

    public static String uploadFile(File file,String RequestURL) {
        String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成
        String PREFIX = "--" , LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; //内容类型
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true); //允许输入流
            conn.setDoOutput(true); //允许输出流
            conn.setUseCaches(false); //不允许使用缓存
            conn.setRequestMethod("POST"); //请求方式
            conn.setRequestProperty("Charset", CHARSET);
            //设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            if(file!=null) {
                /** * 当文件不为空，把文件包装并且上传 */
                OutputStream outputSteam=conn.getOutputStream();
                DataOutputStream dos = new DataOutputStream(outputSteam);
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意：
                 * name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
                 * filename是文件的名字，包含后缀名的 比如:abc.png
                 */
                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END);
                sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while((len=is.read(bytes))!=-1)
                {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功
                 * 当响应成功，获取响应的流
                 */
                int res = conn.getResponseCode();
                Log.e(TAG, "response code:"+res);
                if(res==200)
                {
                    return SUCCESS;
                }
            }
        } catch (MalformedURLException e)
        { e.printStackTrace(); }
        catch (IOException e)
        { e.printStackTrace(); }
        return FAILURE;
    }

    public void refresh() {
        onCreate(null);
    }
}
